package com.yswl.yeeduo.ui.fragment;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.content.LocalBroadcastManager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;

import com.umeng.analytics.MobclickAgent;
import com.yswl.yeeduo.App;
import com.yswl.yeeduo.R;
import com.yswl.yeeduo.http.KAsyncTask.TaskDelegate;
import com.yswl.yeeduo.tool.KStringTool;
import com.yswl.yeeduo.tool.KSystemTool;
import com.yswl.yeeduo.ui.activity.LoginActivity;
import com.yswl.yeeduo.ui.activity.RankingListDetailActivity;
import com.yswl.yeeduo.ui.activity.WebViewActivity;
import com.yswl.yeeduo.ui.adapter.LuckyAdapter;
import com.yswl.yeeduo.ui.bean.ActiviteDetailBean;
import com.yswl.yeeduo.ui.bean.Page;
import com.yswl.yeeduo.ui.task.ActivityListTask;
import com.yswl.yeeduo.ui.tool.ServiceAuthManager;
import com.yswl.yeeduo.ui.tool.ToastUtil;
import com.yswl.yeeduo.view.CommonEmptyView;
import com.yswl.yeeduo.view.dialog.SelectSharePopupDialog;
import com.yswl.yeeduo.view.listview.xlistview.XListView;
import com.yswl.yeeduo.view.listview.xlistview.XListView.IXListViewListener;

/**
 * 用户红包页面
 * 
 * @author Administrator
 * 
 */
public class LuckyMoneyActivityFragment extends Fragment implements TaskDelegate, OnItemClickListener, OnClickListener, IXListViewListener {
	 public static final String TAG="LuckyMoneyActivityFragment";
	 
	public final static int REFLUSH_ID = 20200;
	private final static int LOADMORE_ID = 20222;
	private Page mPage = new Page();

	private XListView mXListView;
	private LuckyAdapter mAdapter;
	private ArrayList<ActiviteDetailBean> mListdata;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View ui = inflater.inflate(R.layout.fragment_luckymoney, null);
		mXListView = (XListView) ui.findViewById(R.id.lm_list);
		mXListView.setOnItemClickListener(this);
		mAdapter = new LuckyAdapter(getActivity(), this);
		mXListView.setPullLoadEnable(true);
		mXListView.setPullRefreshEnable(true);
		mXListView.setXListViewListener(this);
		mXListView.setAdapter(mAdapter);
		CommonEmptyView.setCommonEmptyView(getActivity(), mXListView, null);
		mPage.setCurPage(1);
		getData(REFLUSH_ID);
		
		registerMessageReceiver();
		return ui;
	}

	private void getData(int requestId) {
		if (KSystemTool.isNetworkAvailable(getActivity()) == false) {
			ToastUtil.showShortMsg("请检查网络！");
			return;
		}
		sendActiveRequest(requestId);
	}

	private void setData(ArrayList<ActiviteDetailBean> data, int requestId) {
		if (requestId == REFLUSH_ID) {
			mAdapter.dataList.clear();
			mAdapter.setData(mListdata);
		} else if (requestId == LOADMORE_ID) {
			mAdapter.addData(data);
		}
		mXListView.setRefreshTime(new SimpleDateFormat("HH:mm:ss").format(new Date()));
		mXListView.stopRefresh();
		mXListView.stopLoadMore();
	}

	/**
	 * 活动列表请求
	 */
	public  void sendActiveRequest(final int requestIdType) {
		if (!isAdded()) {
			return;
		}

		Map<String, String> params = new HashMap<String, String>();
		String userId = ServiceAuthManager.getUserId(getActivity());
		if (KStringTool.isEmpty(userId)) {
			userId = "-1";
		}
		params.put("userId", userId);
		params.put("offset", mPage.getStart() + "");// 当前页起始行
		params.put("count", mPage.getPageSize() + "");
		params.put("api_key", ServiceAuthManager.getToken(getActivity()));
		params.put("lng", App.getInstance().longitude);
		params.put("lat", App.getInstance().latitude);
		new ActivityListTask(getActivity(), requestIdType, this).execute(params);

	}

	@Override
	public void faild_TaskDelegate(int taskId, Object object) {
		ToastUtil.showShortMsg(object.toString());
		
		mXListView.stopLoadMore();
		mXListView.stopRefresh();
	}

	@Override
	public void success_TaskDelegate(int taskId, Object object) {
		mListdata = (ArrayList<ActiviteDetailBean>) object;
		mPage.setTotalRow(ActivityListTask.mTotalPage);// 设置总行数
		switch (taskId) {
		case REFLUSH_ID:
			setData(mListdata, REFLUSH_ID);
			break;
		case LOADMORE_ID:
			setData(mListdata, LOADMORE_ID);
			break;

		default:
			break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		ActiviteDetailBean bean = mAdapter.getItem(position - 1);
		getActivity().startActivity(WebViewActivity.createIntent(getActivity(), bean, false, false));
	}

	/**
	 * Um统计
	 */
	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPageStart(this.getClass().getSimpleName());
	}

	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onPageEnd(this.getClass().getSimpleName());
	}

	
	@Override
	public void onClick(View v) {
		int position = (Integer) v.getTag();
		ActiviteDetailBean beanData = mAdapter.getItem(position);
		if (App.getInstance().isLogin == false) {
			getActivity().startActivity(new Intent(getActivity(), LoginActivity.class));
			return;
		}

		if (beanData.flag) {// 已经分享 查看排行榜
			MobclickAgent.onEvent(getActivity(),"user_check_rankinglist");
			getActivity().startActivity(RankingListDetailActivity.createIntent(getActivity(), beanData.activeId));
		} else { // 微信分享
			
//			WXAuthByUm auth = new WXAuthByUm(getActivity());
//			if (beanData != null) {
//				auth.WxShareByUm(beanData);
//				auth.mDelegate = this;
//			}
			
			SelectSharePopupDialog dialog = new SelectSharePopupDialog(getActivity());
			dialog.setActiveBean(beanData); 
			dialog.showAtLocation((LinearLayout)mXListView.getParent(), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
		}

	}

	@Override
	public void onRefresh() {
		mPage.setCurPage(1);
		getData(REFLUSH_ID);
	}

	@Override
	public void onLoadMore() {
		if (mPage.canLoadMore()) {
			mPage.nextPage();
			getData(LOADMORE_ID);
		} else {
//			ToastUtil.showShortMsg("无更多数据");
			mXListView.stopRefresh();
			mXListView.stopLoadMore();
		}
	}


	
	private Handler handle = new Handler(){
		public void handleMessage(android.os.Message msg) {
			if (msg.what == REFLUSH_ID) {
				sendActiveRequest(REFLUSH_ID);
			}
		};
	};
	/**
	 * 对外提供发送启动广播的方法
	 * @param con
	 * @return
	 */
	public static void sendBroadcast(Context con){
		Intent intent = new Intent();
		intent.setAction(LuckyMoneyActivityFragment.MESSAGE_RECEIVED_ACTION);
		LocalBroadcastManager.getInstance(con).sendBroadcast(intent);
	}
	/**
	 *  广播接收者 用来通知数据刷新
	 */
	public static final String MESSAGE_RECEIVED_ACTION = "notification_refresh_data";
	private BroadcastReceiver mReceiver;
	public void registerMessageReceiver() {
		LocalBroadcastManager mBroadcastManager = LocalBroadcastManager.getInstance(getActivity());
		IntentFilter filter = new IntentFilter();
		filter.addAction(MESSAGE_RECEIVED_ACTION);
		mReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
					handle.sendEmptyMessage(REFLUSH_ID);
				}
			}
		};
		mBroadcastManager.registerReceiver(mReceiver, filter);
	}

	// 解除注册广播
	@Override
	public void onDestroy() {
		LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mReceiver);
		super.onDestroy();
	}

}
